<template>
  <div id="app">
    <router-view
      v-if="!isLoggedIn"
      :isSubmitting="isSubmitting"
      :authError="authError"
      @login="handleLogin"
      @register="handleRegister"
      @update:authError="authError = $event"
      @update:isLoggedIn="isLoggedIn = $event"
      :key="$route.fullPath"
    />
    <DashBoard
      v-else
      :username="username"
      :account="account"
      :userType="userType"
      @logout="logout"
      :analyzedVideoUrl="analyzedVideoUrl"
      :setAnalyzedVideoUrl="setAnalyzedVideoUrl"
    />
  </div>
</template>

<script>
// import { jsPDF } from 'jspdf'
import axios from 'axios'
import DashBoard from '@/components/DashBoard.vue'

export default {
  name: 'App',
  components: { DashBoard },
  data() {
    return {
      isLoggedIn: false,
      isSubmitting: false,
      authError: '',
      userType: 'user',
      username: '',
      account: '',
      analysisData: [],
      registeredUsers: [],
      videoUrl: '',
      analyzedVideoUrl: localStorage.getItem('analyzedVideoUrl') || ''
    }
  },
  methods: {
    async handleRegister({ username, password, userType }) {
      this.isSubmitting = true
      

      this.authError = ''
      try {
        const res = await axios.post('/api/users/register', { username, password, userType })
        this.account = res.data.user.account
        this.username = res.data.user.username
        this.isLoggedIn = true
        localStorage.setItem('account', this.account)
        this.$router.push('/home')
      } catch (err) {
        // this.$router.push('/')
        this.authError = err.response?.data?.message || '注册失败'
      } finally {
        this.isSubmitting = false
      }
    },
    async handleLogin(credentials) {
      this.isSubmitting = true
      this.authError = ''
      try {
        const res = await axios.post('/api/users/login', {
          account: credentials.account,
          password: credentials.password
        })
        this.account = res.data.user.account
        this.username = res.data.user.username
        this.isLoggedIn = true
        this.$router.push('/home')
      } catch (err) {
        this.authError = err.response?.data?.message || '登录失败'
      } finally {
        this.isSubmitting = false
      }
    },
    logout() {
      this.isLoggedIn = false;
      this.$router.push('/login')

      this.account = '';
      this.username = '';
      this.userType = 'user';
      this.analyzedVideoUrl = '';
      localStorage.removeItem('currentAnalyzedVideo');
      localStorage.removeItem('originalVideoUrl');
      localStorage.removeItem('analyzedVideoUrl');
    },
    // handleFileUpload(file) {
    //   return new Promise((resolve) => {
    //     this.videoUrl = URL.createObjectURL(file)
    //     setTimeout(() => {
    //       this.analysisData = [
    //         { type: '站立讲解', count: Math.floor(Math.random() * 20) + 5, duration: Math.floor(Math.random() * 1500) + 500 },
    //         { type: '走动巡视', count: Math.floor(Math.random() * 15) + 3, duration: Math.floor(Math.random() * 1000) + 200 },
    //         { type: '板书书写', count: Math.floor(Math.random() * 10) + 1, duration: Math.floor(Math.random() * 800) + 100 }
    //       ]
    //       resolve()
    //     }, 1000)
    //   })
    // },
    // exportPDF() {
    //   const doc = new jsPDF()
    //   doc.setFontSize(18)
    //   doc.setTextColor(52, 152, 219)
    //   doc.text('教师课堂行为分析报告', 105, 20, { align: 'center' })
    //   doc.setFontSize(12)
    //   doc.setTextColor(44, 62, 80)
    //   doc.text(`用户名: ${this.username}`, 20, 30)
    //   doc.text(`账号: ${this.account}`, 20, 40)
    //   doc.text(`生成时间: ${new Date().toLocaleString()}`, 20, 60)
    //   doc.setFontSize(14)
    //   doc.text('行为分析结果:', 20, 80)
    //   let yPos = 90
    //   this.analysisData.forEach(item => {
    //     doc.setFontSize(12)
    //     doc.text(
    //       `${item.type}: ${item.count}次，总时长${item.duration}秒`, 
    //       20, 
    //       yPos
    //     )
    //     yPos += 10
    //   })
    //   doc.save(`教师行为分析_${this.account}_${new Date().toISOString().slice(0,10)}.pdf`)
    // },
    // onLoginSuccess(payload) {
    //   this.isLoggedIn = true;
    //   this.account = payload.account;
    //   this.userType = payload.userType;
    //   this.analyzedVideoUrl = '';
    //   localStorage.removeItem('currentAnalyzedVideo');
    //   localStorage.removeItem('originalVideoUrl');
    //   localStorage.removeItem('analyzedVideoUrl');
    //   this.$router.push('/home');
    // },
    // onRegisterSuccess(payload) {
    //   this.isLoggedIn = true;
    //   this.account = payload.username;
    //   this.userType = payload.userType;
    //   this.analyzedVideoUrl = '';
    //   localStorage.removeItem('currentAnalyzedVideo');
    //   localStorage.removeItem('originalVideoUrl');
    //   localStorage.removeItem('analyzedVideoUrl');
    //   this.$router.push('/home');
    // },
    // setAnalyzedVideoUrl(url) {
    //   this.analyzedVideoUrl = url;
    //   localStorage.setItem('analyzedVideoUrl', url);
    // }
  }
}
</script>